# 此类专门用于搜狗邮箱发邮件，因搜狗邮箱没有开通smtp服务器，所以只能采用exchange服务器发送邮件
from exchangelib import DELEGATE, Account, Credentials, Configuration, NTLM, Message, Mailbox, HTMLBody, FileAttachment, Body
from os.path import dirname, abspath

# from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
# 此句用来消除ssl证书错误，exchange使用自签证书需加上
# HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter


class ExchangeUtil:

    def __init__(self, subject, receiver_list, cc_receiver_list=[], bcc_receiver_list=[], sender='itfin_bigdata_common@sogou-inc.com', password='Fin$Big!Data123'):
        self.sender = sender
        self.password = password
        self.server = 'mail.sogou-inc.com'
        # 校验账号和密码
        cred = Credentials(self.sender, self.password)
        print("账户验证成功")
        # 账户的配置文件
        config = Configuration(server=self.server, credentials=cred, auth_type=NTLM)
        print("配置文件设置成功")
        # 生成账户
        self.account = Account(primary_smtp_address=sender, config=config, autodiscover=False, access_type=DELEGATE)
        print("发邮件主体账户创建成功")
        # 创建发邮件主题
        self.msg_root = Message(account=self.account,
                                folder=self.account.sent,
                                subject=subject,
                                to_recipients=receiver_list,
                                cc_recipients=cc_receiver_list,
                                bcc_recipients=bcc_receiver_list)
        print("邮件root类初始化成功")

    # 创建html的table片段
    @staticmethod
    def create_table_html_fill_color(t_head_data, t_body_data, table_title='表格html'):
        t_head = '<tr><th>' + '</th><th>'.join(map(str, t_head_data)) + '</th></tr>'
        # 对最后一个值进行着色标记
        for i in range(len(t_body_data)):
            if t_body_data[i][-1] == 0:
                if float(t_body_data[i][-2]) < 0:
                    t_body_data[i][-2] = '<font color="blue">↓' + str(round(abs(t_body_data[i][-2]) * 100, 2)) + '%</font>'
                elif float(t_body_data[i][-2]) >= 0:
                    t_body_data[i][-2] = '<font color="red">↑' + str(round(abs(t_body_data[i][-2]) * 100, 2)) + '%</font>'
            elif t_body_data[i][-1] == 1:
                if float(t_body_data[i][-2]) < 0:
                    t_body_data[i][-2] = '<font color="blue">-' + str(round(abs(t_body_data[i][-2]), 2)) + '</font>'
                elif float(t_body_data[i][-2]) >= 0:
                    t_body_data[i][-2] = '<font color="red">+' + str(round(abs(t_body_data[i][-2]), 2)) + '</font>'
            elif t_body_data[i][-1] == 2:
                if float(t_body_data[i][-5]) >= float(t_body_data[i][-2]):
                    t_body_data[i][-5] = '<font color="red">' + str(round(t_body_data[i][-5] * 100, 2)) + '%</font>'
                elif float(t_body_data[i][-5]) <= float(t_body_data[i][-3]):
                    t_body_data[i][-5] = '<font color="blue">' + str(round(t_body_data[i][-5] * 100, 2)) + '%</font>'
                t_body_data[i] = t_body_data[i][:-2]

        t_body = '<tr>' + '</tr><tr>'.join(['<td>' + '</td><td>'.join(map(str, row[:-1])) + '</td>' for row in t_body_data]) + '</tr>'
        t_table = ' <table class="imagetable">%s </table>' % (t_head + t_body)
        t_title = '<h2>%s</h2>' % table_title
        return t_title + t_table

    # 创建html的table片段
    @staticmethod
    def create_table_html(t_head_data, t_body_data, table_title='表格html'):
        t_head = '<tr><th>' + '</th><th>'.join(map(str, t_head_data)) + '</th></tr>'
        t_body = '<tr>' + '</tr><tr>'.join(
            ['<td>' + '</td><td>'.join(map(str, row)) + '</td>' for row in t_body_data]) + '</tr>'
        t_table = ' <table class="imagetable">%s </table>' % (t_head + t_body)
        t_title = '<h2>%s</h2>' % table_title
        return t_title + t_table

    # 替换table片段的标签，创建html正文
    @staticmethod
    def create_html_content_by_replace_table(repalce_data, replace_label='TABLE_BODY'):
        path = dirname(abspath(__file__))
        f = open(path + '/html_template/table_template_2.html', 'r')
        t_content = f.read().replace(replace_label, repalce_data)
        f.close()
        return t_content

    # 添加正文内容
    def set_content(self, content, content_type='plain'):
        if content_type == 'plain':
            self.msg_root.body = Body(content)
        elif content_type == 'html':
            self.msg_root.body = HTMLBody(content)
        print("邮件正文添加成功")

    # 添加附件
    def add_file(self, file_name):
        unabs_file_name = file_name.replace('\\', '/').split('/')[-1]
        with open(file_name, 'rb') as f:
            att = FileAttachment(name=unabs_file_name, content=f.read())
        self.msg_root.attach(att)

    def send(self):
        self.msg_root.send_and_save()

    def reset_msgroot(self, subject, receiver_list, cc_receiver_list, bcc_receiver_list):
        self.msg_root = Message(account=self.account,
                                folder=self.account.sent,
                                subject=subject,
                                to_recipients=receiver_list,
                                cc_recipients=cc_receiver_list,
                                bcc_recipients=bcc_receiver_list)

if __name__ == '__main__':
    subject = 'exchange邮件'
    receiver_list = []
    cc_receiver_list = []
    bcc_receiver_list = ['lirui215278@sogou-inc.com']
    f = open('/Users/ruili/svn/data_scripts/common_util/html_template/aaaa.html', 'r', errors='ignore')
    content = f.read()
    f.close()
    file_name = '../file_log/run_logs/run_log.2018-05-07'

    mail = ExchangeUtil(subject, receiver_list, cc_receiver_list, bcc_receiver_list)
    mail.set_content(content, content_type='html')
    # mail.add_file(file_name)
    mail.send()

